
import csv
from datetime import datetime
import os

from application.config import appSettings
from sanren.extensions import MyLogger
from application.http.models import OemModel
from sanren.utils import Utils


def export_job(*args, **kwargs):
    log = MyLogger('export.job')
    log.logger.info('===============任务-导出表单收集')

    # 下载单信息
    obj_download = OemModel.Download.find(args[0])
    if obj_download is None:
        log.logger.info('===============Export: 找不到此下载单')
        return 700404

    if obj_download.status == 2:
        log.logger.info('===============Export: 此下载单已经完成')
        return 700403

    params = kwargs
    print(params)

    # 获取表单收集数据
    objs = OemModel.CodeCollection.with_('brand').with_('codelog')

    # 时间限制
    if params['start_time'] is not None and params['start_time'] != '' and params['end_time'] is not None and params['end_time'] != '':
        objs = objs.where_between('created_at', f'{params['start_time']} 00:00:00', f'{params['end_time']} 23:59:59')
    # 品牌限制
    if 'brand_id' in params and params['brand_id']:
        objs = objs.where('brand_id', params['brand_id'])
    # 批次信息
    if 'batch_sn' in params and params['batch_sn']:
        objs = objs.where('batch_sn', params['batch_sn'])
    # 防伪码
    if 'security_code' in params and params['security_code']:
        objs = objs.where('security_code', params['security_code'])
    # 序列号
    if 'serial_number' in params and params['serial_number']:
        objs = objs.where('serial_number', params['serial_number'])
    # 关键词搜索 姓名、手机搜索
    if 'keyword' in params and params['keyword']:
        objs = objs.where(
            lambda query: query.where(
                'name', 'like', f'%{params["keyword"]}%'
            ).or_where(
                'phone', 'like', f'%{params["keyword"]}%'
            )
        )

    objs = objs.order_by('id', 'desc').all()

    # if len(objs) < 1:
    #     log.logger.info('===============Export: 导出数据为空')
    #     return 700404

    log.logger.info(f'===============Export: 开始处理表单收集 {params["start_time"]} - {params["end_time"]}')
    # 下载单变更为处理中
    obj_download.status = 1
    obj_download.save()

    # 导出字段配置
    format_header = ["二维码编号", "二维码", "姓名", "手机号码", "微信号", "Email", "扩展字段1", "扩展字段2", "扩展字段3", "扩展字段4", "扩展字段5", "扩展字段6", "表单收集时间"]

    # _file_name = order.batch_sn + '-' + str(order.counts) + '-' + str(Utils.create_random_number(8))
    _file_name = f'表单收集-{params["start_time"]}-{params["end_time"]}-{str(Utils.create_random_number(6))}'
    if not os.path.exists(appSettings.export_path):
        os.makedirs(appSettings.export_path)
    file_name = _file_name + '.csv'
    save_file_path = appSettings.export_path + '/' + file_name

    def write_csv():
        # 1. 创建文件对象
        df = open(save_file_path, 'w', encoding='utf-8')
        # 2. 基于文件对象构建 csv写入对象
        csv_writer = csv.writer(df)
        # 3. 构建列表头
        csv_writer.writerow(format_header)
        # 4. 写入csv文件内容
        # for item in codes:
        for item in objs:
            csv_writer.writerow([
                f'{item.serial_number}【{item.batch_sn}】',
                item.security_code,
                item.name,
                item.phone,
                item.wechat,
                item.email,
                item.ext1,
                item.ext2,
                item.ext3,
                item.ext4,
                item.ext5,
                item.ext6,
                datetime.fromtimestamp(item.created_time).strftime("%Y-%m-%d %H:%M:%S"),
            ])
        # 5. 关闭文件
        df.close()

    try:
        # 生成码包文件
        write_csv()
    except Exception as e:
        log.logger.error(f'===============任务-导出表单收集失败, {e}')
        obj_download.status = 3
        obj_download.save()

    # 下载单
    obj_download.path = file_name
    obj_download.status = 2
    obj_download.save()

    log.logger.info('===============任务-导出完成')
